package com.yz.kronos.schedule.handle;

import com.yz.kronos.schedule.model.RequestDto;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 任务同步器
 * @author shanchong
 * @date 2021/2/6
 **/
public class Synchronizer {
    /**
     * 任务流id:[任务1分片数量,任务2分片数量,任务3分片数量]
     */
    private static final Map<String, List<CountDownLatch>> CACHE = new HashMap<>();

    private final String flowId;

    public Synchronizer(String flowId) {
        this.flowId = flowId;
    }

    public static Synchronizer build(String flowId, final List<RequestDto> requestDtoList) {
        List<CountDownLatch> shareTotalList = requestDtoList.stream().map(e-> new CountDownLatch(e.getShareTotal())).collect(Collectors.toList());
        CACHE.put(flowId, shareTotalList);
        return new Synchronizer(flowId);
    }

    public void await(int index) {
        List<CountDownLatch> list = CACHE.getOrDefault(flowId, new ArrayList<>());
        CountDownLatch atomicInteger = list.get(index);
        try {
            if (atomicInteger != null) {
                boolean await = atomicInteger.await(1, TimeUnit.DAYS);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void unlock(String flowId, int index) {
        List<CountDownLatch> list = CACHE.getOrDefault(flowId, new ArrayList<>());
        CountDownLatch countDownLatch = list.get(index);
        if (countDownLatch != null) {
            countDownLatch.countDown();
        }
    }

    public static void clear(String flowId) {
        CACHE.remove(flowId);
    }

}
